import React, { Component } from 'react'
import {DeviceEventEmitter, Alert,AsyncStorage,BackHandler,View, TouchableOpacity, ScrollView, Text, KeyboardAvoidingView } from 'react-native'
import { connect } from 'react-redux'
import Push from '../Lib/Push'

import { Button, TextInput } from '../Components'

import CheckMobileActions from '../Redux/CheckMobileRedux'
import ValidcodeActions from '../Redux/ValidcodeRedux'
import RegisterActions from '../Redux/RegisterRedux'

// Styles
import styles from './Styles/RegisterScreenStyle'

class RegisterScreen extends Component {
  static navigationOptions = {
    title: '注册'
  }
  constructor(props) {
    super(props)
    this.state = {
      deviceId: null,
      longitude: null,
      latitude: null,
      lastSeconds: 120,
      mobile: null,
      mobileValid: null,
      mobileErrorMsg: null,
      code: null,
      codeValid: null,
      codeErrorMsg: null,
      password: null,
      passwordValid: null,
    }
  }
  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
    Push.getDeviceId((error, result) => {
      if (error) {
        console.error(error)
      } else {
        this.setState({deviceId: result})
      }
    })
    navigator.geolocation.getCurrentPosition((pos)=>{
      var crd = pos.coords
      this.setState({longitude:crd.longitude,latitude:crd.latitude})
      console.tron.log(crd)
    }, (err) => {
      console.warn(`ERROR(${err.code}):${err.message}`)
    })
  }
  componentDidUpdate(prevProps, prevState) {
    if(prevProps.mobile.fetching && !this.props.mobile.error) {
      this.setState({mobileValid:true})
    }
    if(prevProps.mobile.fetching && this.props.mobile.error) {
      this.setState({mobileValid:false,mobileErrorMsg: this.props.mobile.errMsg})
    }
    if(prevProps.validcode.fetching && this.props.validcode.error) {
      this.setState({codeErrorMsg: this.props.validcode.errMsg})
    }
    /** do register **/
    if(prevProps.register.fetching
      && !this.props.register.fetching
      && this.props.register.payload) {
      //setTimeout(this._goHome, 3000)
      console.tron.log('register success')
      DeviceEventEmitter.emit('login')
    }
    if(this.state.lastSeconds <= 0) {
      clearInterval(this.timer)
      this.setState({lastSeconds:120})
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer)
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  onBackPress = () => {
    this.props.navigation.goBack()
    return true
  }
  _goHome = () => this.props.navigation.navigate('LaunchScreen')
  _getValidcode = () => {
    this.props.getValidcode(this.state.mobile)
    this.timer = setInterval(()=>{
      this.setState({lastSeconds:this.state.lastSeconds-1})},1000)
  }
  _checkMobile = () => {
    if(this.state.mobile && this.state.mobile.length === 11) {
      this.props.checkMobile(this.state.mobile)
    } else {
      this.setState({mobileValid:false,mobileErrorMsg:'请输入正确的手机号码'})
    }
  }
  _checkCode = () => {
    if(this.state.code && this.state.code == this.props.validcode.payload) {
      this.setState({codeValid:true})
    } else {
      this.setState({codeValid:false,codeErrorMsg:'验证码错误'})
    }
  }
  _checkPassword = () => {
    if(this.state.password && this.state.password.length >= 6) {
      this.setState({passwordValid:true})
      this.props.doRegister(
        this.state.mobile,
        this.state.password,
        this.state.deviceId,
        this.state.longitude,
        this.state.latitude)
    } else {
      this.setState({passwordValid:false})
    }
  }
  render () {
    const { navigate, goBack } = this.props.navigation
    let mainView = null
    if (!this.state.mobileValid) {
      mainView = (
        <View>
          <Text>手机号码</Text>
          <TextInput
            onChangeText={(mobile)=>this.setState({mobile:mobile})}
            keyboardType='phone-pad'
            placeholder='请输入您的手机号码'
          />
          {this.state.mobileValid === false && <Text style={styles.errorMsg}>{this.state.mobileErrorMsg}</Text>}
          <View style={styles.button}>
            {this.props.mobile.fetching ? (
              <Button title='验证中...' disabled />
            ) : (
              <Button title='下一步' onPress={this._checkMobile} />
            )}
          </View>
        </View>
      )
    } else if (!this.state.codeValid) {
      mainView = (
        <View>
          <Text>验证码</Text>
          <View style={{flexDirection:'row',alignItems:'center',justifyContent:'space-between'}}>
            <View style={{flex:1,marginRight:10}}>
              <TextInput
                onChangeText={(code)=>this.setState({code:code})}
                placeholder='请输入4位验证码'
                keyboardType='numeric'
              />
            </View>
            {this.state.lastSeconds == 120 ? (
              <TouchableOpacity onPress={this._getValidcode}>
                <Text>点击获取验证码</Text>
              </TouchableOpacity>
            ) : <Text>{this.state.lastSeconds}秒重新获取</Text>}
          </View>
          {(this.state.codeValid === false || this.props.validcode.error) && <Text style={styles.errorMsg}>{this.state.codeErrorMsg}</Text>}
          <View style={styles.button}>
            <Button title='下一步' onPress={this._checkCode} />
          </View>
        </View>
      )
    } else if (!this.state.passwordValid) {
      mainView = (
        <View>
          <Text>密码</Text>
          <TextInput secureTextEntry
            onChangeText={(password)=>this.setState({password:password})}
            placeholder='请输入密码(至少6位,包含数字和字母)'
          />
          {this.state.passwordValid === false && <Text style={styles.errorMsg}>请输入密码(至少6位,包含数字和字母</Text>}
          <View style={styles.button}>
          {this.props.register.fetching ?
              <Button title='注册中...' disabled />
              :
              <Button title='注册' onPress={this._checkPassword} />}
          </View>
        </View>
      )
    } else {
      mainView = (
        <View>
          <View style={styles.bigSection}>
            <Text style={{fontSize:18}}>注册成功</Text>
          </View>
          <View style={styles.button}>
            <Button title='前往首页' onPress={this._goHome} />
          </View>
        </View>
      )
    }
    return (
      <View style={styles.container}>
        <KeyboardAvoidingView behavior='position'>
          {mainView}
        </KeyboardAvoidingView>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    mobile: state.checkMobile,
    validcode: state.validcode,
    register: state.register
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    checkMobile: (mobile) => dispatch(CheckMobileActions.checkMobileRequest(mobile)),
    getValidcode: (mobile) => dispatch(ValidcodeActions.validcodeRequest(mobile)),
    doRegister: (mobile,password,deviceId,longitude,latitude) => dispatch(RegisterActions.registerRequest(mobile,password,deviceId,longitude,latitude))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(RegisterScreen)
